package com.ruicar.afs.cloud.manage.common.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.basic.api.corporate.fegin.CorporateTransferFeign;
import com.ruicar.afs.cloud.basic.api.dto.UpdateCustInfoDto;
import com.ruicar.afs.cloud.bizcommon.cms.dto.CmsResponse;
import com.ruicar.afs.cloud.bizcommon.cms.enums.CodeResponseEnum;
import com.ruicar.afs.cloud.bizcommon.cms.enums.SuccessResponseEnum;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.alibaba.fastjson.TypeReference;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.translog.service.GlobalTransService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.enums.ServiceNameEnum;
import com.ruicar.afs.cloud.common.enums.ToBasicSyncDataUrl;
import com.ruicar.afs.cloud.common.modules.contract.enums.*;
import com.ruicar.afs.cloud.manage.cms.service.IcosToCmsChangeRepaymentService;
import com.ruicar.afs.cloud.manage.common.entity.ComAttachementFile;
import com.ruicar.afs.cloud.manage.common.entity.ManageCustInfoChange;
import com.ruicar.afs.cloud.manage.common.mapper.ManageCustInfoChangeMapper;
import com.ruicar.afs.cloud.manage.common.service.ComAttachementFileService;
import com.ruicar.afs.cloud.manage.common.service.ManageCustInfoChangeService;
import com.ruicar.afs.cloud.manage.common.util.CreatCaseNoUtil;
import com.ruicar.afs.cloud.manage.creditchange.condition.CustInfoChangeCondition;
import com.ruicar.afs.cloud.manage.creditchange.enums.BankTemplateIdEnum;
import com.ruicar.afs.cloud.manage.creditchange.vo.CustInfoChangeToCmsVO;
import com.ruicar.afs.cloud.manage.creditchange.vo.CustInfoManageVO;
import com.ruicar.afs.cloud.manage.workflow.entity.WorkTaskCreatedInfo;
import com.ruicar.afs.cloud.manage.workflow.enums.NormalSubmitEnum;
import com.ruicar.afs.cloud.manage.workflow.processor.ContractWorkFlowNoticeProcessor;
import com.ruicar.afs.cloud.manage.workflow.processor.ContractWorkFlowSaveApproveInfoProcessor;
import com.ruicar.afs.cloud.manage.workflow.service.WorkTaskCreatedInfoService;
import com.ruicar.afs.cloud.manage.workflow.service.WorkflowSubmitService;
import com.ruicar.afs.cloud.manage.workflow.vo.TaskSubmitVO;
import com.ruicar.afs.cloud.workflow.api.dto.flowprocess.request.StartFlowRequest;
import com.ruicar.afs.cloud.workflow.gwt.service.WorkflowService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author: Lee
 * @date 2020-05-30 04:45:15
 * @description
 */
@Service
@AllArgsConstructor
public class ManageCustInfoChangeServiceImpl extends ServiceImpl<ManageCustInfoChangeMapper, ManageCustInfoChange> implements ManageCustInfoChangeService {
    private final WorkflowService workflowService;
    private final GlobalTransService globalTransService;
    private final WorkflowSubmitService workflowSubmitService;
    private final CorporateTransferFeign custInfoUpdateService;
    private final ComAttachementFileService comAttachementFileService;
    private final WorkTaskCreatedInfoService workTaskCreatedInfoService;
    private final IcosToCmsChangeRepaymentService icosToCmsChangeRepaymentService;
    private final ContractWorkFlowSaveApproveInfoProcessor saveApproveInfoProcessor;


    /**
     * 保存案件
     *
     * @param manageCustInfoRecord
     */
    @Override
    public ManageCustInfoChange saveCustInfoRecord(CustInfoManageVO manageCustInfoRecord) {
        ManageCustInfoChange custInfoChange = baseMapper.selectOne(Wrappers.<ManageCustInfoChange>lambdaQuery()
                .eq(ManageCustInfoChange::getContractNo, manageCustInfoRecord.getContractNo())
                .notIn(ManageCustInfoChange::getProcessStatus, ProcessStatusEnum.approved, ProcessStatusEnum.refuse));
        //保存信息
        if (custInfoChange == null || custInfoChange.getProcessStatus().equals(ProcessStatusEnum.approved)) {
            manageCustInfoRecord.setId(null);
            manageCustInfoRecord.setCaseNo(null);
            // 生成案件编号
            manageCustInfoRecord.setCaseNo(CreatCaseNoUtil.GeneratorCaseNo(ContractBusinessEnum.custInfoChange));
            //更改状态
            manageCustInfoRecord.setProcessStatus(ProcessStatusEnum.draft);
            manageCustInfoRecord.setApplyDate(DateUtil.date());
            String role = SecurityUtils.getRoles().get(0);//经销商或业务员身份
            //应客户需求，当经销商申请时，创建人显示申请人名字+电话,   申请人为业务人员是，只显示名字
            //TODO CK 目前仅有姓名，需要从进件获取手机号
            if (role.equals(BusinessSourceEnum.SP)) {
                manageCustInfoRecord.setApplyBy(SecurityUtils.getUser().getUserRealName());
            } else {
                manageCustInfoRecord.setApplyBy(SecurityUtils.getUser().getUserRealName());
            }
            save(manageCustInfoRecord);
        } else {
            if (!ProcessStatusEnum.draft.equals(custInfoChange.getProcessStatus())
                    && !ProcessStatusEnum.toBeRepaired.equals(custInfoChange.getProcessStatus())
                    && !ProcessStatusEnum.approved.equals(custInfoChange.getProcessStatus())
                    && !ProcessStatusEnum.refuse.equals(custInfoChange.getProcessStatus())) {
                throw new AfsBaseException(CommonConstants.FAIL, "此合同编号已流程中！");
            }
            baseMapper.update(manageCustInfoRecord, Wrappers.<ManageCustInfoChange>lambdaQuery()
                    .eq(ManageCustInfoChange::getContractNo, manageCustInfoRecord.getContractNo())
                    .notIn(ManageCustInfoChange::getProcessStatus, ProcessStatusEnum.approved, ProcessStatusEnum.refuse));
        }
        custInfoChange = baseMapper.selectOne(Wrappers.<ManageCustInfoChange>lambdaQuery()
                .eq(ManageCustInfoChange::getCaseNo, manageCustInfoRecord.getCaseNo()));

        //将保存的图片的busiNo换成caseNo
        comAttachementFileService.saveFile(custInfoChange.getContractNo(), custInfoChange.getCaseNo(), AttachmentTypeEnum.custInfo.name());
        return custInfoChange;

//        ManageBankCardChange bankCard = manageBankCardChangeService.getOne(Wrappers.<ManageBankCardChange>lambdaQuery()
//                .eq(ManageBankCardChange::getContractNo, manageCustInfoRecord.getContractNo()));


        /**跟客户沟通后，暂时停止身份信息变更与银行卡变更业务的联动*/
        //OCR识别填充数据
        /*ComAttachementFile idFront = comAttachementFileService.getOne(Wrappers.<ComAttachementFile>lambdaQuery()
                .eq(ComAttachementFile::getBusiNo, "custInfo")
                .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.BankChangeBankCardFrontCode.getCode()));
        ComAttachementFile idBack = comAttachementFileService.getOne(Wrappers.<ComAttachementFile>lambdaQuery()
                .eq(ComAttachementFile::getBusiNo, "custInfo")
                .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.BankChangeIdCardFrontCode.getDesc()));
        ComAttachementFile bankFront = comAttachementFileService.getOne(Wrappers.<ComAttachementFile>lambdaQuery()
                .eq(ComAttachementFile::getBusiNo, "custInfo")
                .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.BankChangeIdCardBackCode.getDesc()));
        //申请资料为转成业务编号前，进行ocr识别，填写页面数据
        if (idFront != null && idBack != null && bankFront != null) {
            List<ComAttachementFile> bankCardBacklist = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, manageCustInfoRecord.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.CustInfoBankCardBackCode.getCode()));
            List<ComAttachementFile> bankCardFrontlist = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, manageCustInfoRecord.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.CustInfoBankCardFrontCode.getCode()));
            List<ComAttachementFile> idCardBacklist = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, manageCustInfoRecord.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.CustInfoIdCardBackCode.getCode()));
            List<ComAttachementFile> idCardFrontlist = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, manageCustInfoRecord.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.CustInfoIdCardForontCode.getCode()));
            List<ComAttachementFile> permitList = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, manageCustInfoRecord.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.custInfoPermitTemplate.getCode()));
            BankCardManageVO bankCardManageVO = new BankCardManageVO();
            bankCardBacklist.get(0).setBusiNo("bankCard");
            bankCardFrontlist.get(0).setBusiNo("bankCard");
            idCardBacklist.get(0).setBusiNo("bankCard");
            idCardFrontlist.get(0).setBusiNo("bankCard");
            permitList.get(0).setBusiNo("bankCard");
            bankCardBacklist.get(0).setAttachmentCode(BankTemplateIdEnum.BankChangeBankCardBackCode.getCode());
            bankCardFrontlist.get(0).setAttachmentCode(BankTemplateIdEnum.BankChangeBankCardFrontCode.getCode());
            idCardBacklist.get(0).setAttachmentCode(BankTemplateIdEnum.BankChangeIdCardBackCode.getCode());
            idCardFrontlist.get(0).setAttachmentCode(BankTemplateIdEnum.BankChangeIdCardFrontCode.getCode());
            permitList.get(0).setAttachmentCode(BankTemplateIdEnum.bankCardPermitTemplate.getCode());
            //执行银行卡变更，生成草稿
            ManageBankCardChange bankCardChange = manageBankCardChangeService.saveBankCardRecord(bankCardManageVO);
            *//**OCR识别功能添加*//*
            ComAttachementFile idCardFront = comAttachementFileService.getOne(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, custInfoChange.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.BankChangeIdCardFrontCode.getDesc()));
            ComAttachementFile idCardBack = comAttachementFileService.getOne(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, custInfoChange.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.BankChangeIdCardBackCode.getDesc()));
            ComAttachementFile bankCardFront = comAttachementFileService.getOne(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, custInfoChange.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.BankChangeIdCardBackCode.getDesc()));
            //身份证正面
            OcrDiscernCondition idCardFrontCondition = new OcrDiscernCondition();
            idCardFrontCondition.setCaseCode(custInfoChange.getCaseNo()); //业务编号
            idCardFrontCondition.setInletEnd("PC");//进件端
            idCardFrontCondition.setSysCode("ICOS");//系统标识
            idCardFrontCondition.setFileCode("idCardFront");//文件类型
            idCardFrontCondition.setFileMd5(idCardFront.getFileId());
            IdCardFrontOcrDiscernVo idCardFrontOcrDiscern = contractOCRInterService.getIdCardFrontOcrDiscern(idCardFrontCondition);
            //身份证号
            custInfoChange.setNewCertNo(idCardFrontOcrDiscern.getNumber());
            //身份证反面
            OcrDiscernCondition idCardBackCondition = new OcrDiscernCondition();
            idCardBackCondition.setCaseCode(custInfoChange.getCaseNo()); //业务编号
            idCardBackCondition.setInletEnd("PC");//进件端
            idCardBackCondition.setSysCode("ICOS");//系统标识
            idCardBackCondition.setFileCode("idCardBack");//文件类型
            idCardBackCondition.setFileMd5(idCardBack.getFileId());
            IdCardBackOcrDiscernVo idCardBackOcrDiscern = contractOCRInterService.getIdCardBackOcrDiscern(idCardBackCondition);
            custInfoChange.setNewCertStartDate(idCardBackOcrDiscern.getValidUntil());//有效期截至日期
            custInfoChange.setNewCertEndDate(idCardBackOcrDiscern.getLssueDate());//签发日期
            //银行卡正面
            OcrDiscernCondition bankCardBackCondition = new OcrDiscernCondition();
            bankCardBackCondition.setCaseCode(custInfoChange.getCaseNo()); //业务编号
            bankCardBackCondition.setInletEnd("PC");//进件端
            bankCardBackCondition.setSysCode("ICOS");//系统标识
            bankCardBackCondition.setFileCode("bankCard");//文件类型
            bankCardBackCondition.setFileMd5(bankCardFront.getFileId());
            BankCardOcrDiscernVo bankCardOcrDiscern = contractOCRInterService.getBankCardOcrDiscern(bankCardBackCondition);
            switch (bankCardOcrDiscern.getBankName()) {
                case "中国工商银行":
                    custInfoChange.setNewBank(BankCodeEnum.ICBC.getCode());
                    break;
                case "中国银行":
                    custInfoChange.setNewBank(BankCodeEnum.BOC.getCode());
                    break;
                case "中国邮政储蓄银行":
                    custInfoChange.setNewBank(BankCodeEnum.PSBC.getCode());
                    break;
                case "中国建设银行":
                    custInfoChange.setNewBank(BankCodeEnum.CCB.getCode());
                    break;
            }
            custInfoChange.setNewBankAccount(bankCardOcrDiscern.getBankCardNumber());
        }*/

    }

    /**
     * 案件提交
     *
     * @param manageCustInfoRecord
     */
    @Override
    public void submitCustInfoRecord(CustInfoManageVO manageCustInfoRecord) {
        //有效期校验
        if (manageCustInfoRecord.getNewCertEndDate() != null) {
            certDateCheck(manageCustInfoRecord.getNewCertEndDate(), manageCustInfoRecord.getIdCardDays());
        }
        if (manageCustInfoRecord.getId() == null) {
            //先进行保存之后，才能提交
            throw new AfsBaseException(CommonConstants.FAIL, "合同业务信息请保存！");
        }
        ManageCustInfoChange custInfo = baseMapper.selectById(manageCustInfoRecord.getId());

        String[] idCardFile = new String[2];
        idCardFile[0] = BankTemplateIdEnum.CustInfoIdCardBackCode.getDesc();
        idCardFile[1] = BankTemplateIdEnum.CustInfoIdCardForontCode.getDesc();
        List<ComAttachementFile> custPhoto = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                .eq(ComAttachementFile::getBusiNo, custInfo.getCaseNo())
                .in(ComAttachementFile::getAttachmentCode, idCardFile));
//        List<ComAttachementFile> bankFile = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
//                .eq(ComAttachementFile::getBusiNo, custInfo.getCaseNo())
//                .eq(ComAttachementFile::getAttachmentCode, "4630734679456432128"));
        if (custPhoto.size() < 2) {
            throw new AfsBaseException("身份证正反照不全");
        }
//        if (bankFile.size() < 1) {
//            throw new AfsBaseException("授权书未上传");
//        }
        manageCustInfoRecord.setCaseNo(custInfo.getCaseNo());
        BeanUtils.copyProperties(custInfo,manageCustInfoRecord);
        //提交审核，发起流程
        if (ProcessStatusEnum.draft.equals(manageCustInfoRecord.getProcessStatus())) {
            //状态 审核中
            manageCustInfoRecord.setProcessStatus(ProcessStatusEnum.underReview);
            manageCustInfoRecord.setId(manageCustInfoRecord.getId());
            updateById(manageCustInfoRecord);
            //更新状态，保存记录到代办

            saveApproveInfoProcessor.saveApproveInfo(manageCustInfoRecord, ContractBusinessEnum.custInfoChange,
                    CaseStatusEnum.UNDER_REVIEW, BusinessUrlEnum.CUSTINFO_CHANGE);
            saveApproveInfoProcessor.saveApproveRecord(manageCustInfoRecord, ContractBusinessEnum.custInfoChange);
            //开始流程提供的参数
            StartFlowRequest startFlowRequest = new StartFlowRequest();
            startFlowRequest.setAfsFlowKey(AfsEnumUtil.key(AfsFlowEnum.CUSTINFO_CHANGE));
            startFlowRequest.setBizDataId(String.valueOf(manageCustInfoRecord.getId()));
            startFlowRequest.setFlowName((StringUtils.isEmpty(manageCustInfoRecord.getContractNo()) ? "" : (manageCustInfoRecord.getContractNo()) + "-") + AfsEnumUtil.desc(AfsFlowEnum.CUSTINFO_CHANGE));
            //将对象json化
            String json = JSONObject.toJSONString(manageCustInfoRecord);
            JSONObject custInfoJson = JSONObject.parseObject(json);
            workflowService.startWorkFlow(startFlowRequest, custInfoJson);
        } else if (ProcessStatusEnum.toBeRepaired.equals(manageCustInfoRecord.getProcessStatus())) {
            //更新状态
            manageCustInfoRecord.setProcessStatus(ProcessStatusEnum.repairedUnderReview);
            updateById(manageCustInfoRecord);
            //保存待办任务记录
            saveApproveInfoProcessor.saveApproveInfo(manageCustInfoRecord, ContractBusinessEnum.custInfoChange,
                    CaseStatusEnum.UNDER_REVIEW, BusinessUrlEnum.CUSTINFO_CHANGE);
            //流程审批
            TaskSubmitVO vo = new TaskSubmitVO();
            String json = JSONObject.toJSONString(manageCustInfoRecord);
            JSONObject custInfoJson = JSONObject.parseObject(json);
            vo.setBizData(custInfoJson);
            vo.setReasonType(manageCustInfoRecord.getReasonType());
            vo.setApprovalOpinion(manageCustInfoRecord.getApprovalOpinion() != null ? manageCustInfoRecord.getApprovalOpinion() : null);
            vo.setApprovalOperating("suggestCheckF");
            //操作记录表
            workflowSubmitService.submit(vo);
            manageCustInfoRecord.setProcessStatus(ProcessStatusEnum.repairedUnderReview);
            updateById(manageCustInfoRecord);
        }

    }

    /**
     * 案件审批
     *
     * @param manageCustInfoRecord
     */
    @Override
    public void saveProposalApplicationInfo(CustInfoManageVO manageCustInfoRecord) {
        Boolean flag = false;
        //变更人员为银行卡绑定人员，改变的类型为除变更有效期除外的
        //流程审批
        ManageCustInfoChange custInfo = baseMapper.selectById(manageCustInfoRecord);
        manageCustInfoRecord.setCustName(custInfo.getCustName());
        TaskSubmitVO vo = new TaskSubmitVO();
        String json = JSONObject.toJSONString(manageCustInfoRecord);
        JSONObject custInfoJson = JSONObject.parseObject(json);
        vo.setApprovalOperating(manageCustInfoRecord.getApprovalOperating());
        vo.setApprovalOpinion(manageCustInfoRecord.getApprovalOpinion());
        vo.setBizData(custInfoJson);
        vo.setReasonType(manageCustInfoRecord.getReasonType());
        workflowSubmitService.submit(vo);
        //更新状态
        CaseStatusEnum CaseStatus = ContractWorkFlowNoticeProcessor.CaseStatus;
        ProcessStatusEnum processStatus = ContractWorkFlowNoticeProcessor.processStatus;

        if (AfsEnumUtil.key(NormalSubmitEnum.SUGGEST_CHECK_FINAL).equals(manageCustInfoRecord.getApprovalOperating())) {//通过
            if (ProcessStatusEnum.approved.equals(processStatus)) {
                manageCustInfoRecord.setEndDate(new Date());
                CaseStatus = CaseStatusEnum.APPROVED;
                flag = true;
                processStatus = ProcessStatusEnum.approved;
            }
            manageCustInfoRecord.setProcessStatus(processStatus);
            //保存合同信息变更申请记录 更新状态表
            saveApproveInfoProcessor.saveApproveInfo(manageCustInfoRecord, ContractBusinessEnum.custInfoChange,
                    CaseStatus, BusinessUrlEnum.CUSTINFO_CHANGE);
        } else if (AfsEnumUtil.key(NormalSubmitEnum.SUGGEST_REJECT_FINAL).equals(manageCustInfoRecord.getApprovalOperating())) {//拒绝
            //结束时间  更改拒绝状态
            manageCustInfoRecord.setProcessStatus(ProcessStatusEnum.refuse);
            manageCustInfoRecord.setEndDate(new Date());
            //更新申请表  保存待办任务
            saveApproveInfoProcessor.saveApproveInfo(manageCustInfoRecord, ContractBusinessEnum.custInfoChange,
                    CaseStatusEnum.REFUSE, BusinessUrlEnum.CUSTINFO_CHANGE);
        } else if (AfsEnumUtil.key(NormalSubmitEnum.SEND_BACK).equals(manageCustInfoRecord.getApprovalOperating())) {//退回
            WorkTaskCreatedInfo workTaskCreatedInfo = workTaskCreatedInfoService.getOne(Wrappers.<WorkTaskCreatedInfo>query().lambda()
                            .eq(WorkTaskCreatedInfo::getBizDataId, manageCustInfoRecord.getId().toString())
                    , false
            );
            //初审时返回待补件状态，否则返回上一轮审核
            if ((workTaskCreatedInfo.getTaskMemo()).equals("preliminary")) {
                manageCustInfoRecord.setProcessStatus(ProcessStatusEnum.toBeRepaired);
            } else {
                manageCustInfoRecord.setProcessStatus(ProcessStatusEnum.underReview);
            }
            //保存待办任务记录
            saveApproveInfoProcessor.saveApproveInfo(manageCustInfoRecord, ContractBusinessEnum.custInfoChange,
                    CaseStatusEnum.UNDER_REVIEW, BusinessUrlEnum.CUSTINFO_CHANGE);
        }
        updateById(manageCustInfoRecord);
        if (flag) {//审批完成，身份信信息更新
            ManageCustInfoChange custInfoChange = baseMapper.selectById(manageCustInfoRecord.getId());
            UpdateCustInfoDto dto = new UpdateCustInfoDto();
            dto.setCustNo(custInfoChange.getCustNo());
            dto.setNewName(custInfoChange.getNewName());
            dto.setNewCertNo(custInfoChange.getNewCertNo());
            dto.setNewCertType(custInfoChange.getNewCertType());
            dto.setNewCertStartDate(custInfoChange.getNewCertStartDate());
            dto.setNewCertEndDate(custInfoChange.getNewCertEndDate());
            dto.setContractNo(custInfoChange.getContractNo());
//            if (manageCustInfoRecord.getBankCertNo() == custInfoChange.getOldCertNo() && custInfoChange.getNewCertNo() != null) {
//                dto.setBankCertNo(custInfoChange.getNewCertNo());
//            }
            //TODO CK向basic同步结果
           if (DataSourceEnum.icos == custInfo.getDataSource()) {
                CustInfoChangeToCmsVO cmsVo = new CustInfoChangeToCmsVO();
                cmsVo.setApplicationNo(custInfo.getApplyNo());//申请号
                cmsVo.setApprover(custInfo.getUpdateBy());//审批人
                cmsVo.setCertDeadline(custInfo.getNewCertEndDate());//到期日
                cmsVo.setCertNo(custInfo.getNewCertNo());//证件号
                cmsVo.setCertType(custInfo.getNewCertType());//证件类型
                cmsVo.setName(custInfo.getNewName());//姓名
                cmsVo.setOperatorUser(custInfo.getApplyBy());//操作人
                cmsVo.setOrigin("icos");//来源
                cmsVo.setRequestId(custInfo.getId().toString());//外围系统存储id
                //角色编码（主借人00003，共借人00004，担保人00005）
                if (custInfo.getChangeSubject().equals(PersonRoleTypeEnum.MAIN_PERSON)) {
                    cmsVo.setRoleCode("00003");
                } else if (custInfo.getChangeSubject().equals(PersonRoleTypeEnum.JOINT_PERSON)) {
                    cmsVo.setRoleCode("00004");
                } else {
                    cmsVo.setRoleCode("00005");
                }
                IResponse<Boolean> response = globalTransService.post(String.valueOf(custInfo.getId()), AfsEnumUtil.key(ServiceNameEnum.BASIC), AfsEnumUtil.key(ToBasicSyncDataUrl.SYNC_CHANGE_CUSTINFO_DATA), vo, new TypeReference<Boolean>() {
                });
                if (CommonConstants.FAIL.equals(response.getCode())) {
                    throw new AfsBaseException("身份信息变更结果数据推送至basic服务失败，请重试！");
                }
            } else {
                CmsResponse response = icosToCmsChangeRepaymentService.syncToCmsChangeCustInfoResult(custInfo);
                if (AfsEnumUtil.key(SuccessResponseEnum.FAIL).equals(response.getSuccess()) && !AfsEnumUtil.key(CodeResponseEnum.M10051).equals(response.getCode())) {
                    throw new AfsBaseException("身份信息变更结果数据推送至cms系统失败，请重试！");
                }
            }


            custInfoUpdateService.updateCustInfo(dto);
        }

        /**跟客户沟通后，暂时停止与银行卡业务联动*/
        //变更主体为银行卡绑定人员时，发起银行卡变更联动
        /*if (manageCustInfoRecord.getYesOrNo()) {
//            if (manageCustInfoRecord.getYesOrNo().equals(PersonRoleTypeEnum.MAIN_PERSON)) {
            BankCardManageVO bankCardManageVO = new BankCardManageVO();
            bankCardManageVO.setContractNo(manageCustInfoRecord.getContractNo());
            bankCardManageVO.setOldBankAccount(manageCustInfoRecord.getOldBankAccount());
            bankCardManageVO.setOldCity(manageCustInfoRecord.getOldCity());
            bankCardManageVO.setOldProvince(manageCustInfoRecord.getOldProvince());
            bankCardManageVO.setOldCardholder(manageCustInfoRecord.getCustName());
            bankCardManageVO.setOldBank(manageCustInfoRecord.getOldBank());
            bankCardManageVO.setNewBankAccount(manageCustInfoRecord.getNewBankAccount());
            bankCardManageVO.setCity(manageCustInfoRecord.getCity());
            bankCardManageVO.setProvince(manageCustInfoRecord.getProvince());
            bankCardManageVO.setNewCardholder(manageCustInfoRecord.getNewName());
            bankCardManageVO.setNewBank(manageCustInfoRecord.getNewBank());
            String[] dateList = new String[2];
            dateList[0] = manageCustInfoRecord.getNewCertStartDate().toString();
            dateList[1] = manageCustInfoRecord.getNewCertEndDate().toString();
            bankCardManageVO.setDate(dateList);
            //将上传的两份资料，一份变更为银行卡申请资料
            List<ComAttachementFile> bankCardBacklist = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, manageCustInfoRecord.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.CustInfoBankCardBackCode.getCode()));
            List<ComAttachementFile> bankCardFrontlist = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, manageCustInfoRecord.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.CustInfoBankCardFrontCode.getCode()));
            List<ComAttachementFile> idCardBacklist = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, manageCustInfoRecord.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.CustInfoIdCardBackCode.getCode()));
            List<ComAttachementFile> idCardFrontlist = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, manageCustInfoRecord.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.CustInfoIdCardForontCode.getCode()));
            List<ComAttachementFile> permitList = comAttachementFileService.list(Wrappers.<ComAttachementFile>lambdaQuery()
                    .eq(ComAttachementFile::getBusiNo, manageCustInfoRecord.getCaseNo())
                    .eq(ComAttachementFile::getAttachmentCode, BankTemplateIdEnum.custInfoPermitTemplate.getCode()));

            bankCardBacklist.get(0).setBusiNo("bankCard");
            bankCardFrontlist.get(0).setBusiNo("bankCard");
            idCardBacklist.get(0).setBusiNo("bankCard");
            idCardFrontlist.get(0).setBusiNo("bankCard");
            permitList.get(0).setBusiNo("bankCard");
            bankCardBacklist.get(0).setAttachmentCode(BankTemplateIdEnum.BankChangeBankCardBackCode.getCode());
            bankCardFrontlist.get(0).setAttachmentCode(BankTemplateIdEnum.BankChangeBankCardFrontCode.getCode());
            idCardBacklist.get(0).setAttachmentCode(BankTemplateIdEnum.BankChangeIdCardBackCode.getCode());
            idCardFrontlist.get(0).setAttachmentCode(BankTemplateIdEnum.BankChangeIdCardFrontCode.getCode());
            permitList.get(0).setAttachmentCode(BankTemplateIdEnum.bankCardPermitTemplate.getCode());
            //执行银行卡变更，生成草稿
            ManageBankCardChange bankCardChange = manageBankCardChangeService.saveBankCardRecord(bankCardManageVO);
            //将保存后的数据作为参数进行提交
            BeanUtils.copyProperties(bankCardManageVO, bankCardChange);
            //提交数据，生成案件审核记录
            manageBankCardChangeService.submitBankCardRecord(bankCardManageVO);
        }*/
    }

    @Override
    public IPage getManageCustInfoChangeList(Page page, CustInfoChangeCondition condition) {
        condition.setChangeSubject(StringUtils.isNotEmpty(condition.getChangeSubject()) ? condition.getChangeSubject().toString() : null);
        return baseMapper.getManageCustInfoChangeList(page, condition);
    }


    /**
     * 证件信息验证
     */
    private boolean certDateCheck(Date endDate, String idCardDays) {
        Boolean valid = false;
        Date now = new Date();
        Long days = (endDate.getTime() - now.getTime()) / (24 * 60 * 60 * 1000);
        Long time = new Long(idCardDays);
        if (days.longValue() < time.longValue()) { //身份证有效期大于当前时间20天
            throw new AfsBaseException("身份证有效期未大于当前时间" + time + "天");
        }
        return valid;
    }
}
